import React, { PureComponent, Fragment } from 'react';

import { connect } from 'dva';

import moment from 'moment';

import QueueAnim from 'rc-queue-anim';
import TweenOne from 'rc-tween-one';

import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import StandardTable from '@/containers/StandardTable';
import StandardTableHandle from '@/containers/StandardTable/StandardTableHandle';

import { questions as columns } from '@/commons/columns';

import styles from './style.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, queryRow = {}, form, handleUpdate, handleModalVisible } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleUpdate(Object.assign({}, fieldsValue, queryRow.id ? { method: 'PUT', id: queryRow.id } : { method: 'POST' }));
    });
  };

  return (
    <Modal
      destroyOnClose
      width={500}
      title={queryRow.id ? '编辑常见问题' : '新增常见问题'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={handleModalVisible.bind(null)}
    >
      <FormItem labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} label="问题标题">
        {form.getFieldDecorator('title', {
          initialValue: queryRow.title,
          rules: [{ message: '请输入8～32个字符间的问题标题！', min: 8, max: 32 }],
        })(<Input placeholder="请输入问题标题" />)}
      </FormItem>
      <FormItem labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} label="问题简述">
        {form.getFieldDecorator('brief', {
          initialValue: queryRow.brief,
          rules: [{ message: '请输入16～200个字符间的问题简述！', min: 16, max: 200 }],
        })(<TextArea placeholder="请输入问题简述" autosize={{ minRows: 5, maxRows: 6 }} />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ questions, loading }) => ({
  questions,
  loading: loading.models.questions,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    queryRow: {},
  };

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: queryRow => (
      <Button icon="edit" ghost type="primary" size="small" onClick={this.handleModalVisible.bind(null, queryRow)}>编辑</Button>
    ),
  }];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'questions/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'questions/fetch',
      payload: params,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'questions/remove',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'questions/fetch',
              });

              this.setState(state => ({
                ...state,
                selectedRows: [],
              }));

              message.success(`共有${data}条常见问题删除成功~`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows,
    }));
  };

  handleModalVisible = (queryRow = {}) => {
    const payload = { queryRow };

    if (isNaN(queryRow.id)) {
      Object.assign(payload, {
        modalVisible: false,
      });
    } else {
      Object.assign(payload, {
        modalVisible: true,
      });
    };

    this.setState(state => ({
      ...state,
      ...payload
    }));
  };

  handleUpdate = payload => {
    const { dispatch } = this.props;

    switch (payload.method) {
      case 'PUT':
        dispatch({
          type: 'questions/update',
          payload,
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('常见问题更新失败！');
            } else {
              dispatch({
                type: 'questions/fetch',
              });

              message.success(`序号${payload.id}的常见问题更新成功～`);

              this.handleModalVisible();
            }
          }
        });
        break;
      case 'POST':
        dispatch({
          type: 'questions/add',
          payload,
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('常见问题新增失败！');
            } else {
              dispatch({
                type: 'questions/fetch',
              });

              message.success(`序号${data.id}的常见问题新增成功～`);

              this.handleModalVisible();
            }
          }
        });
        break;
      default:
        message.error('不太清楚你在搞什么破坏');
        break;
    }
  };

  render() {
    const {
      questions: { data, status },
      loading,
    } = this.props;
    const { queryRow, selectedRows, modalVisible } = this.state;

    const parentMethods = {
      queryRow,
      handleUpdate: this.handleUpdate,
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <PageHeaderWrapper 
        title="常见问题" 
        action={moment().format('LLLL')}
      >
        <Card bordered={false}>
          <StandardTableHandle
            status={status}
            selectedRows={selectedRows}
            menuItems={{'remove': <Button type="danger" icon="delete">删除</Button>}}
            action={
              <Button type="primary" icon="plus" onClick={this.handleModalVisible.bind(null, {id: 0})}>新增</Button>
            }
            onToggleTable={this.handleToggleTable}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            scroll={{ x: 1300 }}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;